package com.poi.util;

import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import com.poi.exp.domain.CellModelVO;

public class ExcelOneSheetUtil {

	/**
	 * 拷贝合并单元格
	 * 
	 * @param sheet
	 * @param srcRow
	 * @param desRow
	 */
//	public static void copyMergeRegion(Sheet sheet, int srcRow, int desRow) {
//		for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
//			CellRangeAddress oldRegion = sheet.getMergedRegion(j);
//			if ((oldRegion.getFirstRow() == srcRow) && (oldRegion.getLastRow() == srcRow)) {
//				int oldFirstCol = oldRegion.getFirstColumn();
//				int oldLastCol = oldRegion.getLastColumn();
//				CellRangeAddress newRegion = new CellRangeAddress(desRow, desRow, oldFirstCol, oldLastCol);
//				// System.out.println(desRow+","+desRow+","+oldFirstCol+","+oldLastCol);
//				sheet.addMergedRegion(newRegion);
//			}
//		}
//	}

	// 判断是否需要合并单元格，并记录
	public static void isNeedMergen(Cell originalCell, Cell newCreateCell) {
		String key = createAddressKey(originalCell);
		CellRangeAddress oldAddress = PoiContextUtil.getContext().getSheetModelMap().get(originalCell.getSheet().getSheetName()).getOriginalAddreaaMap().get(key);
		if (null != oldAddress) {
			//新增合并单元格信息
			Map<String, CellRangeAddress> needMap = PoiContextUtil.getContext().getSheetModelMap().get(originalCell.getSheet().getSheetName()).getNeedAddreaaMap();
			//记录新的单元格需要合并
			needMap.put(createAddressKey (newCreateCell), oldAddress);
		}
	}

	// 组合成合并单元格信息key
	public static String createAddressKey(Cell originalCell) {
		return originalCell.getRowIndex() + "_" + originalCell.getColumnIndex();
	}

	// 组合成合并单元格信息key
	public static String createAddressKey(CellRangeAddress oldRegion) {
		return oldRegion.getFirstRow() + "_" + oldRegion.getFirstColumn();
	}

}
